//
//  CXMineViewController.m
//  Travel
//
//  Created by dllo on 15/11/28.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "CXMineViewController.h"
//#import "ZZXuserLikeViewController.h"
#import "ZZXuserNotesLikeViewController.h"
#import "ZZXdelegateImage.h"
#import "ZZXAboutViewController.h"
#import "CXHotCityLikeViewController.h"
#import "KHHRadioViewController.h"
#import "KHHStoryAllPageViewController.h"

@interface CXMineViewController ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate,UIImagePickerControllerDelegate, ChangeImage>

@property (nonatomic, strong) NSMutableArray *rowArray;
@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, strong) NSMutableDictionary *showDic;
@property (nonatomic, strong) ZZXdelegateImage *backImg;
@property (nonatomic, strong) UIVisualEffectView *bV; //高斯模糊
@property (nonatomic, strong) UIVisualEffectView *bV2; //高斯模糊
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIImageView *img;//头像
@property (nonatomic, strong) UISwitch *swi;
@property (nonatomic, copy) NSString *imgPath;
@property (nonatomic, strong) UIImageView *tableViewImage;
@property (nonatomic, assign) NSInteger tag;



@end

@implementation CXMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addScreenEdgePan];
    self.navigationItem.title = @"我的";


    self.sectionArray = [@[@"我的收藏", @"清除缓存", @"边走边听"]mutableCopy];
    self.rowArray = [@[@"每日精选故事", @"精彩游记与专题", @"热门城市"]mutableCopy];

    [self getChangeImgPath];
    [self createTableView];
    
    self.tag = 66;
}

//创建tableView
- (void)createTableView
{
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(70, 0, 0, 0);
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    self.tableViewImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"12ok.png"]];
    self.tableView.backgroundView = self.tableViewImage;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    //设置tableView的contentView距离上边界264
    self.backImg = [[ZZXdelegateImage alloc]initWithFrame:CGRectMake(0, -280, CWIDTH, 280)];
//          [self.backImg sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil];
    self.backImg.contentMode = UIViewContentModeScaleAspectFill;//设置img高度改变时 宽度也改变
    //裁剪
    self.backImg.clipsToBounds = YES;
    self.backImg.userInteractionEnabled = YES;
    self.backImg.delegate = self;
    [self.tableView addSubview:self.backImg];
    
    
    //高斯模糊
    UIBlurEffect *b = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.bV = [[UIVisualEffectView alloc] initWithEffect:b];
    self.bV.alpha = 0.7;
    self.bV.frame = self.view.frame;
    self.bV.userInteractionEnabled = NO;
    [self.backImg addSubview:self.bV];
    

    self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, -50, CWIDTH, 40)];
    self.label.textAlignment = NSTextAlignmentCenter;
    //    GillSans-Bold
    //Georgia-Italic
    self.label.font = [UIFont fontWithName:@"GillSans-Bold" size:28.0f];
    self.label.textColor = [UIColor cyanColor];
    self.label.text = @"心怀天下";
    
    [self.tableView addSubview:self.label];

    
    //更换封面
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CWIDTH - 70, 80, 60, 25)];
    label.text = @"更换封面";
    label.layer.masksToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.cornerRadius = 10;
    label.font = [UIFont systemFontOfSize:10];
    label.textColor = [UIColor colorWithRed:0.13 green:0.65 blue:0.68 alpha:1];
    label.backgroundColor = [UIColor colorWithRed:0.99 green:0.96 blue:0.93 alpha:0.5];
    [self.view addSubview:label];
   
    
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(label.frame.origin.x, label.frame.origin.y + label.frame.size.height, label.frame.size.width, 30)];
    [btn setTitle:@"换为默认" forState:UIControlStateNormal] ;
    [btn setTitleColor:[UIColor colorWithRed:0.13 green:0.65 blue:0.68 alpha:1] forState:UIControlStateNormal] ;
    [btn addTarget:self action:@selector(MorenAction) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:btn];
   
    
//    self.bV2 = [[UIVisualEffectView alloc]initWithEffect:b];
//    self.bV2.alpha = 0.5;
//    self.bV2.frame = self.view.frame;
////    //关闭用户交互
//    self.bV2.userInteractionEnabled = NO;
//    [self.tableView addSubview:self.bV2];
    
}
#pragma mark -换成默认
- (void)MorenAction
{
    self.tableViewImage.image = [UIImage imageNamed:@"12ok.png"];
    [self.tableView reloadData];
    
    //将本地图片写入本地
    NSData *data;
    data = UIImagePNGRepresentation([UIImage imageNamed:@"12ok.png"]);
    [[NSFileManager defaultManager] createFileAtPath:self.imgPath contents:data attributes:nil];
    [[NSFileManager defaultManager]createFileAtPath:self.imgPath contents:data attributes:nil];
}
#pragma mark - 更换图片路径
- (void)getChangeImgPath{
    //更换图片
    //获取Documents文件夹目录
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    //保存图片的路径
    self.imgPath = [imageDocPath stringByAppendingPathComponent:@"image.png"];
}

#pragma mark - 更改图片协议方法
- (void)changeImage
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc]init];
    //静态方法判断设备是否支持图库功能
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerImage.delegate = self;
    //是否可编辑  裁剪
    pickerImage.allowsEditing = YES;
    //跳转到相册页面
    [self presentViewController:pickerImage animated:YES completion:^{
        
    }];

}

#pragma mark - 相册协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    
    // [self dismissViewControllerAnimated:YES completion:nil];
    // 将编辑后的图片保存在image中
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    //当图片不为空时显示图片并保存图片
    if (image != nil) {
        //图片显示在界面上
        self.tableViewImage.image = image;
        
        //以下是保存文件到沙盒路径下
        //把图片转成NSData类型的数据来保存文件
        NSData *data;
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        //保存
        [[NSFileManager defaultManager] createFileAtPath:self.imgPath contents:data attributes:nil];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    
}




#pragma mark - 背景图下滑改变宽高
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //获取当前偏移量
    CGFloat y = scrollView.contentOffset.y;
    
    if (y < - 120 ) {
        CGRect frame = self.backImg.frame;
        frame.origin.y = y; //image 的frame不断往上偏移
        frame.size.height = -y;//collectionview向下偏移了多少 高度就增加多少
        self.backImg.frame = frame;
        
        self.bV.alpha = (350 + y) / 230 - 0.2 ;
        //  NSLog(@"~~~~~~~~~~~~~%f", self.bV.alpha);
    }
    
}


#pragma mark - TableView 分区

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_sectionArray count];
}

#pragma mark - 每个分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_rowArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        cell.clipsToBounds = YES;
        
    }
    
    cell.textLabel.text = self.rowArray[indexPath.row];
//    UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"allRight"]];
//    cell.accessoryView = img;
  
    
    
//    //夜间模式
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"]) {
//        cell.backgroundColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1];
//    }
//    else
//    {
//        cell.backgroundColor = [UIColor whiteColor];
//    }
    
    //接收通知中心
    //    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    //    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeNight) name:@"ISNIGHT" object:user];
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_showDic objectForKey:[NSString stringWithFormat:@"%ld",indexPath.section]]) {
        return 44;
    }
    return 0;
}
//section头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
//section头部显示的内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CWIDTH, 60)];
    
    UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, CWIDTH, 20)];
    myLabel.text = self.sectionArray[section];
    myLabel.textColor = [UIColor whiteColor];
    [header addSubview:myLabel];
    //夜间模式分区
//    if (section == 2) {
        //创建开关
//        self.swi = [[UISwitch alloc]initWithFrame:CGRectMake(CWIDTH - 60, 0, 40, 60)];
//        self.swi.onTintColor = [UIColor colorWithRed:0.37 green:0.73 blue:0.78 alpha:1];
//        [self.swi addTarget:self action:@selector(nightStyle:) forControlEvents:UIControlEventValueChanged];
        //判断开关状态 每次进入这个页面 开关的状态
//        self.swi.on = [[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"];
//        [header addSubview:self.swi];
    
//    }
    
    
    // 单击的 Recognizer ,收缩分组cell
    header.tag = section;
    UITapGestureRecognizer *singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SingleTap:)];
    singleRecognizer.numberOfTapsRequired = 1; //点击的次数 =1:单击
    [singleRecognizer setNumberOfTouchesRequired:1];//1个手指操作
    [header addGestureRecognizer:singleRecognizer];//添加一个手势监测；
    
    return header;
}

#pragma mark - 夜间模式按钮
//- (void)nightStyle:(UISwitch *)swi
//{
//    
//    if ([swi isOn]) {
//        [[NSUserDefaults standardUserDefaults ]setBool:YES forKey:@"isNight"];  //变成夜间模式
//        self.navigationController.navigationBar.barStyle = UIBarStyleBlack; //运营商的颜色
//        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:40/255.0 green:40/255.0  blue:40/255.0  alpha:1];
//        self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:40/255.0 green:40/255.0  blue:40/255.0  alpha:1];
//    }
//    else
//    {
//        [[NSUserDefaults standardUserDefaults ]setBool:NO forKey:@"isNight"];
//        self.navigationController.navigationBar.barStyle = UIBarStyleDefault; //运营商的颜色
//        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.82 green:0.78 blue:0.72 alpha:1];
//        self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:0.82 green:0.78 blue:0.72 alpha:1];
//    }
//    
//    //每次点开按钮 发送通知
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    //通知中心向cell发送通知
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"ISNIGHT" object:user];
//    
//    
//}
#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{

    //根据图片路径载入图片
    UIImage *image = [UIImage imageWithContentsOfFile:self.imgPath];
    if (image == nil) {
        self.tableViewImage.image = [UIImage imageNamed:@"12ok.png"];
        
    } else {
        self.tableViewImage.image = image;
    }
    
}

#pragma mark 展开收缩section中cell 手势监听
-(void)SingleTap:(UITapGestureRecognizer*)recognizer{
    if (recognizer.view.tag == 0) {
        NSInteger didSection = recognizer.view.tag;
        if (!_showDic) {
            _showDic = [[NSMutableDictionary alloc]init];
        }
        NSString *key = [NSString stringWithFormat:@"%ld",didSection];
        if (![_showDic objectForKey:key]) {
            [_showDic setObject:@"1" forKey:key];
            
        } else {
            [_showDic removeObjectForKey:key];
        }
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:didSection] withRowAnimation:UITableViewRowAnimationFade];
        
    }
    //清除缓存
    if (recognizer.view.tag == 1) {
        // 缓存的文件夹
        NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString *string = [NSString stringWithFormat:@"清除缓存(%.2fM)", [self floatWithPath:cachesPath]];
        // alertController
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"%@", string);
            NSLog(@"取消");
        }];
        [alert addAction:({ UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"确定");
            [self removeCache];
        }];
            action;
        })];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (recognizer.view.tag == 3) {
        ZZXAboutViewController *about = [[ZZXAboutViewController alloc]init];
        about.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:about animated:YES];
        //        [UMFeedback feedbackViewController].hidesBottomBarWhenPushed = YES;
        //         [self.navigationController pushViewController:[UMFeedback feedbackViewController] animated:YES];
    }
    if(recognizer.view.tag == 2) {
        KHHRadioViewController *radio = [[KHHRadioViewController alloc] init];
        
        [self.navigationController pushViewController:radio animated:YES];
        
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        KHHStoryAllPageViewController *like = [[KHHStoryAllPageViewController alloc]init];
        like.tag = self.tag;
        like.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:like animated:YES];
            
    } else if(indexPath.row == 1) {
        ZZXuserNotesLikeViewController *notesLike = [[ZZXuserNotesLikeViewController alloc]init];
        notesLike.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:notesLike animated:YES];
            
    } else {
        CXHotCityLikeViewController *hotcityVC = [[CXHotCityLikeViewController alloc] init];
        [self.navigationController pushViewController:hotcityVC animated:YES];
    }

}



     /********************************************************************/
#pragma mark - 清除缓存
// 删除缓存
- (void)removeCache
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *p in files) {
        NSString * path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
    }
}
// 遍历文件夹获得文件夹大小，返回多少M
- (CGFloat)floatWithPath:(NSString *)path
{
    CGFloat num = 0;
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:path]) {
        NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [path stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    return num / (1024.0 * 1024.0);
}

//计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)file
{
    
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:file]) {
        return [[man attributesOfItemAtPath:file error:nil] fileSize];
    }
    return 0;
}

#pragma mark-滑动手势1
- (void)addScreenEdgePan
{
    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
    screenEdgePan.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:screenEdgePan];
    [self.tableView addGestureRecognizer:screenEdgePan];
    
}
#pragma mark-滑动手势2
-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
